package com.temdemo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author 晨曦
 * @title: StringUtils
 * @projectName iss-stategrid
 * @description: TODO
 * @date 2019/12/913:39
 */
public class StringHelperUtils {
    private final static Logger log = LoggerFactory.getLogger(StringHelperUtils.class);

    /**
     * @return java.lang.String
     * @Description //创建随机数列
     * @Author 晨曦
     * @Date 2019/12/10 13:58
     * @Param [length] 设定随机数长度
     */
  /*  public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }*/
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        StringBuffer sb = new StringBuffer();
        try {
            SecureRandom random2 = SecureRandom.getInstance("SHA1PRNG");
            for (int i = 0; i < length; i++) {
                int number = random2.nextInt(base.length());
                sb.append(base.charAt(number));
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage());
        }
        return sb.toString();
    }


    public static String getSHA256(String str) {
        MessageDigest messageDigest;
        String encodestr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodestr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodestr;
    }

    /**
     *     * 将byte转为16进制
     *     * @param bytes
     *     * @return
     *     
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}
